import 'dart:async';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/widgets.dart' hide Action;
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:oktoast/oktoast.dart';
import 'package:school_safe_teacher/base/base_entity.dart';
import 'package:school_safe_teacher/constans/all_info.dart';
import 'package:school_safe_teacher/constans/route_constants.dart';
import 'package:school_safe_teacher/me/entity/userEntity.dart';
import 'package:school_safe_teacher/network/dio_api.dart';
import 'package:school_safe_teacher/network/http_api.dart';
import 'package:school_safe_teacher/resourse/app_colors.dart';
import 'package:school_safe_teacher/utils/cache_utils.dart';
import 'package:school_safe_teacher/utils/sp_utils.dart';


import 'action.dart';
import 'state.dart';

Effect<ChangePwdState> buildEffect() {
  return combineEffects(<Object, Effect<ChangePwdState>>{
    Lifecycle.initState:_init,
    ChangePwdAction.getCodeCLick: _onGetCode,
    ChangePwdAction.changePwd:_changePwd,
  });
}

void _init(Action action, Context<ChangePwdState> ctx) {
  if (AllInfo.instance.token.isNotEmpty) {
    UserEntity userInfoEntity = AllInfo.instance.userEntity;
    ctx.state..mobile = userInfoEntity.mobile.toString();
    ctx.state.phoneController..text = userInfoEntity.mobile.toString();
    ctx.dispatch(ChangePwdActionCreator.onAction());
  }
}

void _onGetCode(Action action, Context<ChangePwdState> ctx) {
  if (ctx.state.mobile.length != 11) {
    showToast('请输入手机号');
    return;
  }
  Map<String, String> params = Map();
  params["mobile"] = ctx.state.mobile;
  params["type"] = "3";
  DioApi.instance.asyncRequestNetwork<BaseEntity>(Method.post, HttpApi.GET_CODE,ctx.context,
      params: params, onStart: () {
        println('请求开始');
        EasyLoading.show(status: 'loading...');
      }, onSuccess: (dynamic t) async {
        //请求成功
        ctx.state
          ..countdownTime = 60
          ..textColor = AppColors.smallTextColor;
        ctx.state
          ..countdownTimer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
            if (ctx.state.countdownTime < 1) {
              ctx.state.countdownTimer.cancel();
              ctx.state
                ..countdownTime = 0
                ..countdownString = "发送验证码"
                ..textColor = AppColors.cantClickTextColor;
            } else {
              ctx.state..countdownTime = ctx.state.countdownTime - 1;
              ctx.state..countdownString = "${ctx.state.countdownTime}s后重发";
            }
            ctx.dispatch(ChangePwdActionCreator.onAction());
          });
      }, onError: (String msg) {
        println('请求报错 msg:$msg');
        showToast(msg);
      }, onDone: () {
        EasyLoading.dismiss();
      }, isList: false);
}

void _changePwd(Action action, Context<ChangePwdState> ctx){
  Map<String, String> params = Map();
  params["mobile"] = ctx.state.mobile;
  params["sms_code"] = ctx.state.code;
  params["new_password"] = ctx.state.pwd;
  DioApi.instance.asyncRequestNetwork<BaseEntity>(
      Method.post, HttpApi.CHANGE_PWD,ctx.context,
      params: params, onStart: () {
    println('请求开始');
    EasyLoading.show();
  }, onSuccess: (dynamic t) {
    showToast("修改成功，请重新登录");
    clearApplicationCache();
    AllInfo.instance.setToken("");
    AllInfo.instance.setUserinfo("");
    AllInfo.instance.setPhone("");
    AllInfo.instance.setUserEntity(UserEntity());
    AllInfo.instance.setPhone("");
    SpUtil.clear();
    Navigator.of(ctx.context).pushNamedAndRemoveUntil(
        RouteConstants.LOGIN, ModalRoute.withName(RouteConstants.LOGIN));
  }, onError: (String msg) {
    println('请求报错 msg:$msg');
    showToast(msg);
  }, onDone: () {
    EasyLoading.dismiss();
  }, isList: false);
}